package com.aya.server;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.Delimiters;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class SimpleChatServerInitializer extends
        ChannelInitializer<SocketChannel> implements ApplicationContextAware {

    @Resource
    SimpleChatServerHandler simpleChatServerHandler;

    @Resource
    MvcChannelInboundHandler mvcChannelInboundHandler;
    private ApplicationContext applicationContext;

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();

//        pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
//        pipeline.addLast("decoder", new StringDecoder());
//        pipeline.addLast("encoder", new StringEncoder());
        pipeline.addLast("decoder",new ByteArrayDecoder());
        pipeline.addLast("encoder",new ByteArrayEncoder());
//        pipeline.addLast("handler", new MvcChannelInboundHandler());
        MvcChannelInboundHandler bean = applicationContext.getBean(MvcChannelInboundHandler.class);
        pipeline.addLast("handler",bean);
//        pipeline.addLast("handlerb", simpleChatServerHandler);
        System.out.println("SimpleChatClient:"+ch.remoteAddress() +"连接上");
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {

        this.applicationContext = applicationContext;
    }
}